/**
 * @author cqb 2017-01-05.
 * @module Switch
 */

import React from 'react';
import classNames from 'classnames';
import FormItem from '../FormItem';
import './Switch.less';

/**
 * Switch 类
 * @class Switch
 * @constructor
 * @extend BaseComponent
 */
class Switch extends React.PureComponent {
    static displayName = 'Switch';

    static defaultProps = {
        value: false,
        labels: []
    };

    /**
     * switch change回调
     * @return {[type]} [description]
     */
    toggleSwitch = async () => {
        if (this.props.disabled) {
            return;
        }
        let ret = true;
        if (this.props.onBeforeChange) {
            ret = await this.props.onBeforeChange(this.props.value);
        }
        if (ret && this.props.onChange) {
            this.props.onChange(!this.props.value);
        }
    }

    render () {
        let {className, style, labels, size, name, value, disabled} = this.props;
        className = classNames('cm-switch', className, {
            [`cm-switch-${size}`]: size,
            'cm-switch-checked': value,
            'cm-switch-disabled': disabled
        });

        const text = value ? labels[0] : labels[1];

        return (
            <div className={className} style={style} tabIndex='0' onClick={this.toggleSwitch}>
                <span className='cm-switch-inner'>{text}</span>
                <input name={name} type='hidden' value={value ? 1 : 0} />
            </div>
        );
    }
}

FormItem.register(Switch, 'switch');

export default Switch;
